package com.ueip.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ueip.backend.mapper.PositionMapper;
import com.ueip.backend.mapper.UserInfoMapper;
import com.ueip.backend.mapper.UserMapper;
import com.ueip.backend.pojo.Position;
import com.ueip.backend.pojo.User;
import com.ueip.backend.pojo.UserInfo;
import com.ueip.backend.service.UserInfoService;
import com.ueip.backend.utils.IDCardValidator;
import com.ueip.backend.utils.IdentityAuthenticationUtil;
import com.ueip.backend.utils.PhoneNumberValidator;
import com.ueip.backend.vo.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private PositionMapper positionMapper;

    @Resource
    private UserMapper userMapper;
    @Override
    public Result selectPage(Map<String, String> data) {
        // 提取当前用户
        User curUser = IdentityAuthenticationUtil.getCurUser();
        try {
            Integer pageSize = Integer.parseInt(data.get("pageSize"));
            Integer curPageNum = Integer.parseInt(data.get("curPageNum"));
            List<UserInfo> userInfos = userInfoMapper.mySelectPage(pageSize, (curPageNum - 1) * pageSize);
            Map<Integer, String> map = positionMapper.selectList(null).stream().collect(Collectors.toMap(Position::getId, Position::getName, (key1, key2) -> key1 ));
            Map<Integer, String> map1 = userMapper.selectList(null).stream().collect(Collectors.toMap(User::getId, User::getUsername, (key1, key2) -> key1 ));
            for (UserInfo ui : userInfos) {
                ui.setPositionName(map.get(ui.getPositionId()));
                ui.mySetStateName();
                ui.setUsername(map1.get(ui.getId()));
            }
            return Result.ok(userInfos);
        } catch (Exception e) {
            return Result.error("数据有误");
        }
    }

    @Override
    public Result getUserInfosLength() {
        return Result.ok(userInfoMapper.selectCount(null));
    }

    @Override
    public Result deleteById(Map<String, String> data) {
        // 提取当前用户
        User curUser = IdentityAuthenticationUtil.getCurUser();
        try {
            Integer id = Integer.parseInt(data.get("id"));

            UserInfo userInfo = userInfoMapper.selectById(id);

            if (userInfo == null ) {
                return Result.error("该用户信息不存在或已被删除");
            }
            userInfoMapper.deleteById(userInfo);
            return Result.ok("success");
        } catch (Exception e) {
            return Result.error("数据有误");
        }
    }

    @Override
    public Result update(Map<String, String> data) {
        // 提取当前用户
        User curUser = IdentityAuthenticationUtil.getCurUser();
        try {
            Integer id = Integer.parseInt(data.get("id"));
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            List<UserInfo> list = userInfoMapper.selectList(queryWrapper);
            if (list.isEmpty()) {
                return Result.error("该用户信息不存在或已被删除");
            }
            String name = data.get("name");
            String phoneNumber = data.get("phoneNumber");
            String idNum = data.get("idNum");
            Integer positionId = Integer.parseInt(data.get("positionId"));
            Integer state = Integer.parseInt(data.get("state"));

            // 判断职位id是否存在
            QueryWrapper<Position> positionQueryWrapper = new QueryWrapper<>();
            positionQueryWrapper.eq("id", positionId);
            List<Position> positions = positionMapper.selectList(positionQueryWrapper);
            if (positions.isEmpty()) {
                return Result.error("职位不存在或已被删除");
            }

            // 判断用户工作状态是否合法 0：离职 1：在职
            if (state < 0 || state > 1) {
                return Result.error("状态错误");
            }

            // 简单判断姓名的合法性
            if (name == null || name.length() == 0 || name.length() > 20) {
                return Result.error("姓名数据非法");
            }

            // 简单判断电话的合法性
            if (phoneNumber != null && !"".equals(phoneNumber) && !PhoneNumberValidator.isValidPhoneNumber(phoneNumber)) {
                return Result.error("电话数据非法");
            }

            // 简单判断身份证的合法性
            if (idNum != null && "".equals(idNum) && IDCardValidator.isValidIDCard(idNum)) {
                return Result.error("身份证数据非法");
            }
            list.get(0).setName(name);
            list.get(0).setPhoneNumber(phoneNumber);
            list.get(0).setIdNum(idNum);
            list.get(0).setPositionId(positionId);
            list.get(0).setState(state);
            userInfoMapper.updateById(list.get(0));
            return Result.ok("success");
        } catch (Exception e) {
            return Result.error("数据有误");
        }
    }

    @Override
    public Result add(Map<String, String> data) {
        try {
            String name = data.get("name");
            String phoneNumber = data.get("phoneNumber");
            String idNum = data.get("idNum");
            Integer positionId = Integer.parseInt(data.get("positionId"));
            Integer state = Integer.parseInt(data.get("state"));

            String username = data.get("username");
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("username", username);
            User user = userMapper.selectOne(userQueryWrapper);

            if (user == null) {
                return Result.error("用户名不存在或已被删除，无法为其创建对应的用户信息");
            }

            Integer uid = user.getId();

            // 判断职位id是否存在
            QueryWrapper<Position> positionQueryWrapper = new QueryWrapper<>();
            positionQueryWrapper.eq("id", positionId);
            List<Position> positions = positionMapper.selectList(positionQueryWrapper);
            if (positions.isEmpty()) {
                return Result.error("职位不存在或已被删除");
            }

            // 判断用户工作状态是否合法 0：离职 1：在职
            if (state < 0 || state > 1) {
                return Result.error("状态错误");
            }

            // 判断是否有一样信息的用户
            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.eq("name", name);
            userInfoQueryWrapper.eq("phone_number", phoneNumber);
            userInfoQueryWrapper.eq("id_num", idNum);
            List<UserInfo> userInfos = userInfoMapper.selectList(userInfoQueryWrapper);
            if (!userInfos.isEmpty()) {
                return Result.error("该用户信息已存在");
            }

            // 简单判断姓名的合法性
            if (name == null || name.length() == 0 || name.length() > 20) {
                return Result.error("姓名数据非法");
            }

            // 简单判断电话的合法性
            if (phoneNumber != null && !"".equals(phoneNumber) && !PhoneNumberValidator.isValidPhoneNumber(phoneNumber)) {
                return Result.error("电话数据非法");
            }

            // 简单判断身份证的合法性
            if (idNum != null && "".equals(idNum) && IDCardValidator.isValidIDCard(idNum)) {
                return Result.error("身份证数据非法");
            }

            // 判断uid对应的userinfo是否存在
            QueryWrapper<UserInfo> userInfoQueryWrapper1 = new QueryWrapper<>();
            userInfoQueryWrapper1.eq("uid", uid);
            UserInfo userInfo = userInfoMapper.selectOne(userInfoQueryWrapper1);

            if (userInfo != null) {
                userInfoMapper.updateById(new UserInfo(userInfo.getId(), uid, name, phoneNumber, idNum, positionId, state));
            } else {
                userInfoMapper.insert(new UserInfo(null, uid, name, phoneNumber, idNum, positionId, state));
            }

            return Result.ok("success");
        } catch (Exception e) {
            return Result.error("数据有误");
        }
    }

    @Override
    public Result updatePersonalInfo(Map<String, String> data) {
        // 提取当前用户
        User curUser = IdentityAuthenticationUtil.getCurUser();
        try {
            Integer id = Integer.parseInt(data.get("id"));
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            List<UserInfo> list = userInfoMapper.selectList(queryWrapper);
            if (curUser.getId() != list.get(0).getUid()) {
                return Result.error("您没有权限修改他人的信息");
            }
            if (list.isEmpty()) {
                return Result.error("该用户信息不存在或已被删除");
            }
            String name = data.get("name");
            String phoneNumber = data.get("phoneNumber");
            String idNum = data.get("idNum");


            // 简单判断姓名的合法性
            if (name == null || name.length() == 0 || name.length() > 20) {
                return Result.error("姓名数据非法");
            }

            // 简单判断电话的合法性
            if (phoneNumber == null || phoneNumber.length() == 0 || phoneNumber.length() > 20) {
                return Result.error("电话数据非法");
            }

            // 简单判断身份证的合法性
            if (idNum == null || idNum.length() == 0 || idNum.length() > 20) {
                return Result.error("身份证数据非法");
            }

            list.get(0).setName(name);
            list.get(0).setPhoneNumber(phoneNumber);
            list.get(0).setIdNum(idNum);
            userInfoMapper.updateById(list.get(0));
            return Result.ok("success");
        } catch (Exception e) {
            return Result.error("数据有误");
        }
    }
}
